#include "request.h"
#include <algorithm>
#include "utils.h"

using namespace bhttp;

request::request(const std::string& path, const bhttp::method& tp)
    : path_(path)
    , method_(tp)
{

}

request::~request()
{

}

void request::path(const std::string& path)
{
    path_ = path;
}

const std::string& request::path() const
{
    return path_;
}

void request::method(const bhttp::method& tp)
{
    method_ = tp;
}

const bhttp::method& request::method() const
{
    return method_;
}

void request::timeout(int secs)
{
    timeout_ = secs;
}

int request::timeout() const
{
    return timeout_;
}

void request::auth_type(const bhttp::auth& type)
{
    auth_type_ = type;
}

const bhttp::auth& request::auth_type() const
{
    return auth_type_;
}

void request::auth_data(const std::string& data)
{
    auth_data_ = data;
}

const std::string& bhttp::request::auth_data() const
{
    return auth_data_;
}

void request::body(const std::string& str)
{
    body_.assign(str.data(), str.data() + str.size());
}

void request::body(const char* buffer, size_t len)
{
    body_.assign(buffer, buffer + len);
}

const char* request::body() const
{
    return body_.data();
}

size_t request::body_size() const
{
    return body_.size();
}

void request::headers(const std::map<std::string, std::string>& hds)
{
    for (auto it = hds.cbegin(); it != hds.cend(); it++)
    {
        header(it->first, it->second);
    }
}

const std::vector<std::string>& request::headers() const
{
    return headers_;
}

void request::header(const std::string& key, const std::string& value)
{
    headers_.erase(std::remove_if(headers_.begin(), headers_.end(), [key](const std::string& head) {
        return std::string::npos != head.find(key);
    }), headers_.end());
    headers_.emplace_back(key + ": " + value);
}

std::string request::header(const std::string& key)
{
    for (const auto& head : headers_)
    {
        std::string k, v;
        utils::split(head, ":", &k, &v);
        if (utils::strip(key) == k)
            return v;
    }
    return std::string();
}

void request::parmas(const std::map<std::string, std::string>& parmas)
{
    parmas_ = parmas;
}

void request::parma(const std::string& key, const std::string& value)
{
    parmas_[key] = value;
}

std::string request::parma(const std::string& key)
{
    return parmas_[key];
}

const std::map<std::string, std::string>& request::parmas() const
{
    return parmas_;
}
